package com.phx.serialjni;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.phx.serialjni.BaseActivity;
import com.phx.serialjni.MeziView;
import com.phx.uart.uartJni;
import com.phx.uart.uartJnit;
import com.utils.CRC16;
import com.utils.TransformUtils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.net.Socket;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import static com.phx.serialjni.startActivity.makeStatusBarTransparent;


public class MainActivityf extends BaseActivity implements SeekBar.OnSeekBarChangeListener{
  //  public class MainActivityf extends BaseActivity  {
    public static String SOCKET_ADDRESS = "com.clzk.mobilej.local";
    private SeekBar seekBar;
    private SeekBar seekBar1;
    private SeekBar seekBar2;
    private SeekBar seekBar3;

    String headerData = "5aa5";
    byte[] read_buf = new byte[512];
    int fd;
    TextView testView;
     TextView testtView;
     TextView testfView;
    SharedPreferences userInfo;
    String messagercv;
    MeziView mezi;

    Handler handler = new Handler();
    @SuppressLint("HandlerLeak")
    public Handler uHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch(msg.what)
            {
                case 0:
                    break;


                case 1:
                    String commandTxt = msg.getData().getString("alltext");
                    //if (commandTxt.length() > 10)

                  //
//                    if(PageS.pageno == 2)
//                    {
//                        if (commandTxt.length() > 10) {
//                            getvoltage(commandTxt);
//                        }
//                    }
//                    else
//
//                    {
                        testtView.setText(commandTxt);
                        if (commandTxt.length() > 10) {

                            try {
                                refreshallui(commandTxt);
                            }
                            catch (Exception ex)
                            {
                                return;
                            }

                        }
           //  }



                    break;
                default:
                    break;
            }
        }
    };


     private  void getvoltage(String comingdata)
     {
         // String vheaderData = "";
         String message = comingdata;
         if (comingdata.length() >= 40) {
             message = comingdata.substring(0, 40);
         }
         // String message = comingdata;
         String firstFour = message.substring(0, 4);


         int positionInBoard = 0;


         if (firstFour.equals(headerData)) {
             int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
             message = message.substring(0, msgcounts * 2 + 6);
         }
         else {
             return;
         }

         int counts = 0;
         if (message.length() > 19) {

             int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
             counts = (msgcounts - 7) / 2 + 1;

             String[] feedDevice = new String[counts];
             String[] feedStatus = new String[counts];

             if (counts == 1) {


                 String feedDevicex = message.substring(8, 12);

                 String deviceStaus = message.substring(12, 16);

                 Message msg = new Message();
                 //  if (isSend) {
                 msg.what = 2;
                 // msg.obj = deviceStaus;
                 Bundle bundle = new Bundle();
                 bundle.putString("feedDevice", feedDevicex);
                 bundle.putString("feedStatus", deviceStaus);
                 msg.setData(bundle);
                if (feedOK(feedDevicex)) {
                    PageS.feedMap.put(feedDevicex, deviceStaus);
                }
                 mHandler.sendMessage(msg);
             } else {
                 for (int cc = 0; cc < counts; cc++) {
                     feedDevice[cc] = TransformUtils.getAddress(message.substring(8, 12), cc);
                     feedStatus[cc] = message.substring(12 + cc * 4, 16 + cc * 4);

                     Message msg = new Message();
                     //  if (isSend) {
                     msg.what = 1;
                     Bundle bundle = new Bundle();
                     bundle.putString("feedDevice", feedDevice[cc]);
                     bundle.putString("feedStatus", feedStatus[cc]);
                     msg.setData(bundle);
                     if (feedOK(feedDevice[cc])) {
                         PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
                     }
                     mHandler.sendMessage(msg);
                 }
             }
         }
     }
     private  boolean  checkability(String comingdata)
     {
         boolean result = false;

         try {
             int alllength = comingdata.length() - 3;
             String firstFour = "";
             if ((comingdata.length()) > 4) {
                 firstFour = comingdata.substring(0, 4);
                 if (firstFour.equals(headerData)) {
                     int msgcounts = Integer.parseInt(comingdata.substring(4, 6), 16);
                     if (alllength == (msgcounts * 2 + 3)) {
                         result = true;
                     }
                     //   int countsw = (msgcounts - 7) / 2 + 1;
                     //  message = message.substring(0, countsw * 2 + 6);
                 }
             }
         }
         catch(Exception ex)
         {
             result = false;
         }
         return result;
     }

    private  void refreshallui(String comingdata)
    {
        if(!checkability(comingdata)) {
           return;
        }

        String message = "";
        if (comingdata.length() >= 40) {
           message = comingdata.substring(0, 40);
        }
        else
        {
            message = comingdata;
        }
       // String message = comingdata;
        String firstFour ="";
        if((message.length())> 4)
{                firstFour = message.substring(0, 4);
}

                int positionInBoard = 0;


//                if (firstFour.equals(headerData)) {
//                    int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
//                    int countsw = (msgcounts - 7) / 2 + 1;
//                 //  message = message.substring(0, countsw * 2 + 6);
//                }
//                else {
//                    return;
//                }

                   int counts = 0;
                if (message.length() > 19) {

                    int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
                    counts = (msgcounts - 7) / 2 + 1;

                    String[] feedDevice = new String[counts];
                    String[] feedStatus = new String[counts];

                    if (counts == 1) {


                        String feedDevicex = message.substring(8, 12);

                        String deviceStaus = message.substring(12, 16);

                        Message msg = new Message();
                        //  if (isSend) {
                     //   msg.what = 1;
                       // .get(PageS.feedDArray[jmpPostionx]);
                        String ntype = PageS.feedType.get(feedDevicex);
                        msg.what = Integer.parseInt(ntype);
                        // msg.obj = deviceStaus;
                        Bundle bundle = new Bundle();
                        bundle.putString("feedDevice", feedDevicex);
                        bundle.putString("feedStatus", deviceStaus);
                        msg.setData(bundle);
                        if (feedOK(feedDevicex)) {
                            PageS.feedMap.put(feedDevicex, deviceStaus);
                        }
                        mHandler.sendMessage(msg);
                    } else {
                        for (int cc = 0; cc < counts; cc++) {
                            feedDevice[cc] = TransformUtils.getAddress(message.substring(8, 12), cc);
                            feedStatus[cc] = message.substring(12 + cc * 4, 16 + cc * 4);

                            Message msg = new Message();
                            //  if (isSend) {
                            String ntype = PageS.feedType.get( feedDevice[cc]);
                            msg.what = Integer.parseInt(ntype);
                          //  msg.what = 1;
                            Bundle bundle = new Bundle();
                            bundle.putString("feedDevice", feedDevice[cc]);
                            bundle.putString("feedStatus", feedStatus[cc]);
                            msg.setData(bundle);
                            if (feedOK(feedDevice[cc])) {
                                PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
                            }
                            mHandler.sendMessage(msg);
                        }
                    }
                }
    }

    SharedPreferences.OnSharedPreferenceChangeListener mListener = new SharedPreferences
            .OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            String msg = sharedPreferences.getString("user_info", "0000");
           // tv.setText("sp token:" + token);
            Log.e("coming data", "sp token:" + msg);

          //  testView.setText("okokoko");
            //String fStatus = msg.obj.toString();
//            String myjmpposition = msg.getData().getString("jmppageno");
//            jmpPostion = Integer.parseInt(myjmpposition);
//            //  String myStatus = msg.getData().getString("feedStatus");
//
//            //  pagestatus.jmpPosition = Integer.parseInt(pagestatus.cmdArray[1]);
//            //  jmpPostion = pagestatus.jmpPosition;
//
//            //      if ((currentPage!=jmpPostion)&&(TransformUtils.IsInArray(src,jmpPostion + ""))) {
//
//            if ((currentPage!=jmpPostion)&&(TransformUtils.IsInArray(src,jmpPostion + ""))) {
//
//                refreshui(jmpPostion);
//            }
        }
    };


    // MeziView mezi1;
    //  final MeziView mezi;
    // final FrameLayout frame;
    MeziView newm;
    int currentPage = 0;
    PageS pagestatus = new PageS();
    Rect currentRect = new Rect();
    int maxC = 0;
    myFrameLayout frame;




   // pagestatus.

//    public PageS getPagestatus() {
//        return pagestatus;
//    }
   // pagestatus.setInit(currentPage);
    int currentC = 0;
    GridLayout gv;
    Rect tempRect = new Rect();
    //定义16个按钮的文本
    String[] chars = new String[]{
            "7", "8", "9", "%",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            ".", "0", "=", "+"
    };

    String cmdheader = "5AA50883";
    String feedheader = "5AA5";
    static int lType = 1;


    //    氛围灯调暗	0xD1D00009
//    氛围灯调亮	0xD1F00009
//    氛围灯开关	0xD1E00009
//    阅读灯调暗	0xC1D00009
//    阅读灯调亮	0xC1F00009
//    阅读灯开关	0xC1E00009
//    右中门开关	0x08A0000A
//    左中门开关	0x07A1000A
//    右桌板关闭	0xB271000E
//    右桌板打开	0xB161000E
//    左桌板关闭	0x7271000E
//    左桌板打开	0x7161000E
    String[] lcmd1Array = {
            "D1E00009",
            "C1E00009",
            "7161000E",
            "B161000E",
            "7271000E",
            "B271000E",
            "B271000E" //电子钟 需查找

    };
    String[] lhArray = {"00d1", "00c1", "0071", "00b1", "0072", "00b2", "00b2"};
    String[] rhArray = {"0048", "0047", "004B", "004a", "00d1", "004e", "004d"};
    String[] lcmd2Array = {
            "383000",
            "373000",
            "3B3000",

    };

    String[] rcmd1Array = {
            "482000",
            "472000",
            "4B2000",

    };
    String[] rcmd2Array = {
            "483000",
            "473000",
            "4B3000",

    };


    String[] sendCmd1 = {"17201F",
            "18201F",
            "D1E000",
            "123456s",
            "123456hs",
            "123456q",
            "123456stpc",
            "any command",
            "123456pt",
            "123456rvm",
            "123456sdm"};

    String[] sendCmd2 = {"17301F",
            "18301F",
            "1234567sht",
            "123456s",
            "123456hs",
            "123456q",
            "123456stpc",
            "any command",
            "123456pt",
            "123456rvm",
            "123456sdm"};

    private static final long TIMER_INTERVAL = 100;


    static BufferedReader socketBufferedReader = null;
    static PrintWriter socketPrintWriter = null;
    // private GridViewAdapter adapter;
    public int currentPosition = -1;
    String[] countries = new String[]{"电视升", "电视降", "电视电源", "DVD", "顶灯", "上氛围灯", "吧台灯", "下氛围灯", "靠背前", "靠背后", "滑轮前", "滑轮后", "脚托升", "脚托降"};
    //
//    String[] sendCmd = new String[]{"5AA508830101010002F3D5",
//            "5AA508830104010001B26C",
//            "5AA5088303010100025215",
//            "5AA508830401010002E3D4",
//            "5AA508830501010002B214",
//            "5AA5088306010100024214",
//            "5AA50883070101000213D4",
//            "5AA50883080101000223D7",
//            "5AA5088309010100027217",
//            "5AA508830A010100028217",
//            "5AA508830B01010002D3D7",
//            "5AA508830C010100026216",
//            "5AA508830803010001B89C",
//            "5AA508830102010002F391"};
//String[] sendCmd = new String[]{"5AA50883010101000473D7",
//    "5AA50883010201000543D4",
//    "5AA508830103010001B253",
//    "5AA508830104010001A3D5",
//    "5AA508830105010001F215",
//    "5AA5088301060100010215",
//    "5AA50883010701000153D5",
//    "5AA50883010801000163D6",
//    "5AA508830201010002B7D5",
//    "5AA508830202010002B791",
//    "5AA508830203010002B66D",
//    "5AA508830204010002B719",
//    "5AA508830205010002B6E5",
//    "5AA508830206010002B6A1"};
    String[] sendType = new String[]{"02", "01", "01", "01",
            "01", "01", "01", "01",
            "01", "02", "02", "02",
            "02", "02"};

    //    String[] feedCode = new String[] {"0001","0003","0005","0006",
//                                      "0007","0008","0009","0010",
//                                      "0011","0012","0013","0014",
//                                      "0008","0002"};
    String[] feedClose = new String[]{"5aa50d8200d1000000000000000034cb", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e", "5aa5078200030000ac1e"};
    String[] feedLight = new String[]{"5aa50d8200d1000100010000000019cb", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde"};
    String[] feedDian = new String[]{"5AA50883173001001F74E3", "5AA50883183001001F20E2", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde"};

    private List<Integer> mDatas;
    private List<Integer> feedDatas;
    private GridView mGridView;
    private Socket socket = null;
    private String content = "";
    private boolean isRun = true;
  //  private MessageBackReciver mReciver;
    private IntentFilter mIntentFilter;
    private LocalBroadcastManager mLocalBroadcastManager;
    private int newPosition = -1;
    private int jmpPostion = -1;
    ImageButton arrow1;

    ImageButton arrow2;


    public static void expandViewTouchDelegate(final View view, final int top, final int bottom,
                                               final int left, final int right) {

        ((View) view.getParent()).post(new Runnable(){
            @Override
            public void run(){
                Rect bounds = new Rect();
                view.setEnabled(true);
                view.getHitRect(bounds);

                bounds.top -= top;
                bounds.bottom += bottom;
                bounds.left -= left;
                bounds.right +=right;

                TouchDelegate touchDelegate = new TouchDelegate(bounds, view);

                if (View.class.isInstance(view.getParent())) {
                    ((View) view.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });
    }



    public  boolean feedOK(String entr)
    {
        boolean feedx = false;
       // new String[]{"0071", "0072", "0073", "0074","0075","0076","0081", "0082", "0083", "0084","0085","0086","0087","1010","1011","1012","1013","1014"};
       // String[] tmpAll = new String[]{"0071", "0072", "0073", "0074","0075","0076","0081", "0082", "0099", "0099","0099","0086","0087","1010","1011","71b0","72b0","73b0"};
        String[] tmpAll = new String[]{"0071", "0072", "0073", "0074","0081", "0082","0086","0087",
               "1010","1011","71b0","72b0","73b0","74b0"};
        return  TransformUtils.isAvail(tmpAll,entr);
    }

//    class MessageBackReciver extends BroadcastReceiver {
//        // private WeakReference<GridView> gridView;
//
//        public MessageBackReciver() {
//            // gridView = new WeakReference<GridView>(gv);
//        }
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            // TODO Auto-generated method stub
//            String action = intent.getAction();
//            Log.e("receiveTAG", "action");
//            String headerData = "5aa5";
//
//            if (action.equals(BackService.HEART_BEAT_ACTION)) {
//
//            } else if (action.equals(BackService.STATE_SUCCESS_ACTION)) {
//                String message = intent.getStringExtra("message");
//             //    messagercv =  messagercv.substring(0, 25);
//
//
////                runOnUiThread(new Runnable() {
////                    void run() {
////                        // do something
////                        testView.setText(messagercv);
////                    }
////                });
//
//              //  TransformUtils.comingdata = message.substring(0, 25);;
//                String firstFour = message.substring(0, 4);
//
//
//                int positionInBoard = 0;
//
//
//                if (firstFour.equals(headerData)) {
//                    int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
//                    message = message.substring(0, msgcounts * 2 + 6);
//                }
//
//                if (message.length() > 19) {
//
//                    int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
//                    int counts = (msgcounts - 7) / 2 + 1;
//
//                    String[] feedDevice = new String[counts];
//                    String[] feedStatus = new String[counts];
//
//                    //check feedDevice valid
//                 //   if(feedOK(feedDevic))
//
//                    /////////////
//
//
//
//                    //////////////
//
//                    if (counts == 1) {
//
//
//                        String feedDevicex = message.substring(8, 12);
//
//                        String deviceStaus = message.substring(12, 16);
//
//                        Message msg = new Message();
//                        //  if (isSend) {
//                        msg.what = 1;
//                        // msg.obj = deviceStaus;
//                        Bundle bundle = new Bundle();
//                        bundle.putString("feedDevice", feedDevicex);
//                        bundle.putString("feedStatus", deviceStaus);
//                        msg.setData(bundle);
//                        if(feedOK(feedDevicex))
//                        {
//                            PageS.feedMap.put(feedDevicex,deviceStaus);
//                        }
//                        mHandler.sendMessage(msg);
//                    } else {
//                        for (int cc = 0; cc < counts; cc++) {
//                            feedDevice[cc] = TransformUtils.getAddress(message.substring(8, 12), cc);
//                            feedStatus[cc] = message.substring(12 + cc * 4, 16 + cc * 4);
//
//                            Message msg = new Message();
//                            //  if (isSend) {
//                            msg.what = 1;
//                            Bundle bundle = new Bundle();
//                            bundle.putString("feedDevice", feedDevice[cc]);
//                            bundle.putString("feedStatus", feedStatus[cc]);
//                            msg.setData(bundle);
//                            if(feedOK(feedDevice[cc]))
//                            {
//                                PageS.feedMap.put(feedDevice[cc],feedStatus[cc]);
//                            }
//                            mHandler.sendMessage(msg);
//                        }
//                    }
//
//
//                    if (newPosition != -1) {
//                        //  if(sendType[newPosition].equals("01")) {
//
//                        //adapter.update(newPosition, resultStatus);
//                        //  adapter.notifyDataSetChanged();
//                        // }
//
//                    }
//                }
//
//            } else if (action.equals(BackService.STATE_FAIL_ACTION)) {
//
//            } else {
//                String message = intent.getStringExtra("message");
//
//            }
//        }
//    }
//receive
    //5aa5118200f1000000010001000000000000adff0000000000000000000000000000000000000000000000000000000000000000000000000000000000
    //send
    //5AA50883F310000E001B5D

    public boolean getFeedType(String value) {
        boolean result = false;
        String test = value.substring(12, 16);
        if (test.equals("0001")) {
            result = true;
        }
        return result;
    }

    public boolean getDeviceCode(String value) {
        boolean result = false;
        String test = value.substring(9, 10);
        if (test.equals("0001")) {
            result = true;
        }
        return result;
    }


    public boolean findFeedStatus(String value) {
        boolean result = false;
        String test = value.substring(12, 16);
        if (test.equals("0001")) {
            result = true;
        }
        return result;
    }


    public String findFeedIndexy(String test) {
        for (int i = 0; i < feedClose.length; i++) {
            //String deviceCode = getDeviceCode(sendCmd[i]);
            if (feedClose[i].equals(test)) {
                return "00" + i;
            }
        }
        for (int i = 0; i < feedLight.length; i++) {
            //String deviceCode = getDeviceCode(sendCmd[i]);
            if (feedClose[i].equals(test)) {
                return "11" + i;
            }
        }
        return "-1";
    }

    public int findNewPosition(String test) {
        for (int i = 0; i < TransformUtils.feedCode.length; i++) {
            //String deviceCode = getDeviceCode(sendCmd[i]);
            if (TransformUtils.feedCode[i].equals(test)) {
                return i;
            }
        }

        return -1;
    }

    private View getTouchTarget(View view, int x, int y) {
        View targetView = null;
        // 判断view是否可以聚焦
        ArrayList<View> TouchableViews = view.getTouchables();
        for (View child : TouchableViews) {
            if (isTouchPointInView(child, x, y)) {
                targetView = child;
                break;
            }
        }
        return targetView;
    }


    public int findFeedIndex(String test) {
        for (int i = 0; i < TransformUtils.sendCmd.length; i++) {
            String banCode = TransformUtils.sendCmd[i].substring(8, 10);
            String keyCode = TransformUtils.sendCmd[i].substring(10, 12);
            int banInt = Integer.parseInt(banCode, 16);
            int keyInt = Integer.parseInt(keyCode, 16);
            int deviceInt = (banInt - 1) * 20 + keyInt;
            String deviceCode = String.valueOf(deviceInt);
            int testInt = Integer.parseInt(test, 16);
            if (testInt == deviceInt) {
                return i;
            }

        }
        return -1;

    }


    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // tv_msg.setText(content);
            // change GridView
            switch (msg.what) {


                case 0:

                    Toast mToast = Toast.makeText(MainActivityf.this, "请检查网络设置", Toast.LENGTH_SHORT);
                    mToast.show();

                    break;
                case 1://在收到消息时，对界面进行更新
                    // String fStatus = Integer.parseInt(msg.obj.toString());


                    String myDevice = msg.getData().getString("feedDevice");
                    String myStatus = msg.getData().getString("feedStatus");
                  //  if (lType == 1) {
                        int myPosition = TransformUtils.findPosition(PageS.feedDArray, myDevice);
                        if (myPosition != -1) {
                          //  MeziView newm = new MeziView();
                           // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
                          //  MeziView  newm = getaddMezi(myPosition);
                          // testFeed(myPosition);
                            boolean fstt = myStatus.equals("0001") ? true:false;
                            testFeed(myPosition,fstt);
                            Log.e("feegTag","myposition");

//                            if (myStatus.equals("0001")) {
//
//                                if(newm != null)
//                                {
//
//                                    newm.mRes = PageS.onArray[myPosition];
//                                }
//                               // ctlBtn[myPosition].setBackgroundResource(onArray[myPosition]);
//                            } else {
//                               // newm.mRes = PageS.offArray[myPosition];
//
//                                if(newm != null)
//                                {
//
//                                    newm.mRes = PageS.onArray[myPosition];
//                                }
//                               // ctlBtn[myPosition].setBackgroundResource(offArray[myPosition]);
//                            }
                     //   }
//                    } else {
//                        int myPosition = TransformUtils.findPosition(rhArray, myDevice);
//                        if (myPosition != -1) {
//                            if (myStatus.equals("0001")) {
//                                ctlBtn[myPosition].setBackgroundResource(onArray[myPosition]);
//                            } else {
//                                ctlBtn[myPosition].setBackgroundResource(offArray[myPosition]);
//                            }
//                        }
                    }

                    break;
                case 2://在收到消息时，对界面进行更新
                    // String fStatus = Integer.parseInt(msg.obj.toString());


                    String myDevicex = msg.getData().getString("feedDevice");
                    String myStatusx = msg.getData().getString("feedStatus");
                    disv(myDevicex,myStatusx);
                    //  if (lType == 1) {
//                    int myPositionx = TransformUtils.findPosition(PageS.feedDArray, myDevicex);
//                    if (myPositionx != -1) {
//                        //  MeziView newm = new MeziView();
//                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
//                        //  MeziView  newm = getaddMezi(myPosition);
//                        // testFeed(myPosition);
//                        boolean fstt = myStatusx.equals("0001") ? true:false;
//                        testFeed(myPositionx,fstt);
//                        Log.e("feegTag","myposition");
//
//
//                    }

                    break;
                case 3:
                    String[] src = {"0","1","2","3","4","5"};

                    //通过 Bundle传过来

                    String fStatus = msg.obj.toString();
                    String myjmpposition = msg.getData().getString("jmppageno");
                    jmpPostion = Integer.parseInt(myjmpposition);
                  //  String myStatus = msg.getData().getString("feedStatus");

                  //  pagestatus.jmpPosition = Integer.parseInt(pagestatus.cmdArray[1]);
                  //  jmpPostion = pagestatus.jmpPosition;

              //      if ((currentPage!=jmpPostion)&&(TransformUtils.IsInArray(src,jmpPostion + ""))) {

                    if ((currentPage!=jmpPostion)&&(TransformUtils.IsInArray(src,jmpPostion + ""))) {

                        refreshui(jmpPostion);
                    }
                    break;

                case 4://在收到消息时，对界面进行更新
                    // String fStatus = Integer.parseInt(msg.obj.toString());
                    String fStatusx = msg.obj.toString();
                    String myStatusa = "0001";
                    String myjmppositionx = msg.getData().getString("jmppageno");
                    int jmpPostionx = Integer.parseInt(myjmppositionx);

                    if (jmpPostionx!= -1) {
                        myStatusa = PageS.feedMap.get(PageS.feedDArray[jmpPostionx]);
                        //  MeziView newm = new MeziView();
                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
                        //  MeziView  newm = getaddMezi(myPosition);
                        // testFeed(myPosition);
                        boolean fstt = myStatusa.equals("0001") ? false:true;
                        testFeed(jmpPostionx,fstt);
                        Log.e("feegTag4", myStatusa);

                    }

                    break;

                case 5://在收到消息时，对界面进行更新
                    // String fStatus = Integer.parseInt(msg.obj.toString());
                    String fStatusxy = msg.obj.toString();
                    String myStatusay = "0000";
                    String myjmppositionxy = msg.getData().getString("jmppageno");
                    int jmpPostionxy = Integer.parseInt(myjmppositionxy);
                    if (jmpPostionxy!= -1) {
                        myStatusay = PageS.feedMap.get(PageS.feedDArray[jmpPostionxy]);
                        //  MeziView newm = new MeziView();
                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
                        //  MeziView  newm = getaddMezi(myPosition);
                        // testFeed(myPosition);
                        boolean fstt = myStatusay.equals("0001") ? true:false;
                        testFeed(jmpPostionxy,fstt);
                        Log.e("feegTag5",myStatusay);

                    }

                    break;

                case 6://在收到消息时，对界面进行更新
                    // String fStatus = Integer.parseInt(msg.obj.toString());


                    String myDevicex6 = msg.getData().getString("feedDevice");
                    String myStatusx6 = msg.getData().getString("feedStatus");
                    dish(myDevicex6,myStatusx6);
                    //  if (lType == 1) {
//                    int myPositionx = TransformUtils.findPosition(PageS.feedDArray, myDevicex);
//                    if (myPositionx != -1) {
//                        //  MeziView newm = new MeziView();
//                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
//                        //  MeziView  newm = getaddMezi(myPosition);
//                        // testFeed(myPosition);
//                        boolean fstt = myStatusx.equals("0001") ? true:false;
//                        testFeed(myPositionx,fstt);
//                        Log.e("feegTag","myposition");
//
//
//                    }

                    break;
                default:
                    break;

            }
        }
    };

     void  dish(String device,String stat)
     {
         if(PageS.allDArray[10].equals(device)){
             //  int fir = Integer.parseInt(stat.substring(2,3));
             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
             int value = fir * 16 + sec;
//             float lastx = (float) 0.0;
//             lastx = (float)(value/10.0);
//             NumberFormat formatter = new DecimalFormat("0.0");

             //String formmatedFloatValue = formatter.format(lastx);
             if((value> -1) && (value < 101)) {
              //   testView.setText(formmatedFloatValue);
                 if(seekBar!=null)
                 {
                     seekBar.setProgress(value);
                 }
             }
         }
         if(PageS.allDArray[11].equals(device)){
             //  int fir = Integer.parseInt(stat.substring(2,3));
             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
             int value = fir * 16 + sec;
//             float lastx = (float) 0.0;
//             lastx = (float)(value/10.0);
//             NumberFormat formatter = new DecimalFormat("0.0");

             //String formmatedFloatValue = formatter.format(lastx);
             if((value> -1) && (value < 101))  {
                 //   testView.setText(formmatedFloatValue);
                 if(seekBar1!=null)
                 {
                     seekBar1.setProgress(value);
                 }
             }
         }
         if(PageS.allDArray[12].equals(device)){
             //  int fir = Integer.parseInt(stat.substring(2,3));
             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
             int value = fir * 16 + sec;
//             float lastx = (float) 0.0;
//             lastx = (float)(value/10.0);
//             NumberFormat formatter = new DecimalFormat("0.0");

             //String formmatedFloatValue = formatter.format(lastx);
             if((value> -1) && (value < 101))  {
                 //   testView.setText(formmatedFloatValue);
                 if(seekBar2!=null)
                 {
                     seekBar2.setProgress(value);
                 }
             }
         }

         if(PageS.allDArray[13].equals(device)){
             //  int fir = Integer.parseInt(stat.substring(2,3));
             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
             int value = fir * 16 + sec;
//             float lastx = (float) 0.0;
//             lastx = (float)(value/10.0);
//             NumberFormat formatter = new DecimalFormat("0.0");

             //String formmatedFloatValue = formatter.format(lastx);
             if((value> -1) && (value < 101))  {
                 //   testView.setText(formmatedFloatValue);
                 if(seekBar3!=null)
                 {
                     seekBar3.setProgress(value);
                 }
             }
         }
     }


     void  disv(String device,String stat)
     {
         if(PageS.voladdress[0].equals(device)){
           //  int fir = Integer.parseInt(stat.substring(2,3));
             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
             int value = fir * 16 + sec;
             float lastx = (float) 0.0;
             lastx = (float)(value/10.0);
             NumberFormat formatter = new DecimalFormat("0.0");

             String formmatedFloatValue = formatter.format(lastx);
             if((lastx > 9.9) && (lastx < 14.6)) {
                 if(testView == null) {

                 }
                 else {
                     testView.setText(formmatedFloatValue);
                 }
             }
         }
         if(PageS.voladdress[1].equals(device)){
             int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
             int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
             int value = fir * 16 + sec;
            // int value = BigInteger(fir,16);
             float lasty = (float) 0.0;
             lasty = (float)(value/10.0);
             NumberFormat formatter = new DecimalFormat("0.0");

             String formmatedFloatValue = formatter.format(lasty);
             if((lasty > 9.9) && (lasty < 14.6)) {
                 if(testfView == null) {

                 }
                 else {
                     testfView.setText(formmatedFloatValue);
                 }
             }
         }
     }
    public void slidersend(int seekno,int sseq )
    {
        String cmdx = PageS.sliderCmd[seekno][sseq];
        // String tmpTmp = "C1200009";
        String cmdheader = "5AA50883";
        String feedheader = "5AA5";
        String allCmdx = cmdheader;
        String tmpTmp = cmdx;
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        final String cmd = allCmd.substring(0, 22);
        // String crcString = "83192001001F";
        //  String crcString =  pagestatus.cmdArray[currentPosition];
        //  String nexts = "5aa5078200030000ac1e";
        // String crcString = cmdOne ;
        //   StringBuffer exCmd = CRC16.crc16(crcString);
        new Thread() {
            public void run() {
                super.run();
                try {
                    //   if (uartJint != null) {
                    boolean isSendx = false;
                    isSendx = uartJnit.getInstance().sendCmds(cmd);
                    Log.e("send TAG", "send down: " + cmd);
                    Message msg = new Message();
                    if (isSendx) {
                        //  msg.what = 1;

                        Log.e("send TAG", "send down" + cmd + "success");
                    } else {
                        Log.e("TAG", "send down  :" + cmd + "failed!");
                    }
                    //    }
//
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep((long) TIMER_INTERVAL);
                } catch (InterruptedException e2) {
                    e2.printStackTrace();

                }
            }


        }.start();
    }
    //数值改变

   public  String  revertValue (int value)
    {
        int fir = value/16;
        int sec = value%16;
        String res = "00";
        StringBuffer sb = new StringBuffer(res);
        sb.append(CRC16.convertF(fir));
        sb.append(CRC16.convertF(sec));
          return  sb.toString();
        //int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
        //int sec = Integer.parseInt(stat.substring(3));
       // int value = fir * 16 + sec;

    }
    @Override
    public void onProgressChanged(SeekBar seekBarx, int progress,
                                  boolean fromUser) {
        // TODO Auto-generated method stub
      //  tv1.setText("正在拖动");
        //  testView.setText("当前数值："+progress);
        //PageS.allDArray

        int type = 0;
        int tmp = (int) seekBarx.getTag();
        int firpara = progress / 10 ;
//        if (feedOK(feedDevice[cc])) {
//            PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
//        }
        String myvalue = revertValue(firpara * 10);
                 if (feedOK(PageS.allDArray[10+tmp])) {
             PageS.feedMap.put(PageS.allDArray[10+tmp], revertValue(firpara * 10));
        }


        //  testView.setText("当前数值："+ firpara);
        if(firpara < 10) {
         //   String cmdx = PageS.sliderCmd[tmp][firpara];
            String cmdx = PageS.sliderCmd[tmp][firpara];
            if (progress % 10 == 0) {
      //          testtView.setText("当前数值：" + cmdx);

                try {
                    slidersend(tmp, firpara);
                }
                catch(Exception ex)
                {
                    return;
                }
            }
        }

    }

    //开始拖动
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
       // tv1.setText("开始拖动");
    }

    //停止拖动
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
      //  tv1.setText("停止拖动");
    }



    public void removeAll()
    {
        if (frame != null) {
            frame.removeAllViews();
            frame.invalidate();
        }
       maxC = 0;
    }

    public  void createSeekb()
    {
        seekBar = new SeekBar(this);


//        <SeekBar
//        android:id="@+id/brseekBar"
//        android:layout_width="280dp"
//        android:layout_height="wrap_content"
//        android:layout_gravity="top|left"
//        android:layout_marginTop="300dip"
//        android:maxHeight="3dip"
//        android:minHeight="3dip"
//        android:progressDrawable="@drawable/adjust"
//        android:thumb="@drawable/thumb_image"
//        android:thumbOffset="0dip"></SeekBar>
       // seekBar.setThumb(getDrawable(R.drawable.thumb_image));
    //    Drawable drawable = getNewDrawable(MainActivityf.this,R.drawable.thumb_image, 24, 24);
        //   seekBar.setThumb(drawable);
        seekBar.setThumb(getDrawable(R.drawable.thumb_image));
        seekBar.setProgressDrawable(getDrawable(R.drawable.adjust));
        seekBar.setMinimumHeight(convertHn(3));
      //  seekBar.setOnSeekBarChangeListener(this);
       // seekBar.setThumbOffset(0);
      //s  seekBar.setProgress(80);
   //     frame = (myFrameLayout) findViewById(R.id.gridlayout1);
        //  seekBar.buildLayer();
        // seekBar.setTop(100);
        //    seekBar.setLeft(500);
        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(403), convertHn(45));
        //   View headGroupView = UIUtils.inflate(mContext,R.layout.circle_head_layout);
//        RelativeLayout rlHead = (RelativeLayout)headGroupView.findViewById(R.id.rl_circle_head);
//        ImageView headImage = (ImageView)headGroupView.findViewById(R.id.iv_head_small);
        //headParams.setMargins(convertWn(566), convertHn(95), convertWn(936), convertHn(198));
      //  headParams.setMargins(convertWn(566), convertHn(95), convertWn(936), convertHn(198));
        headParams.leftMargin = convertWn(363);
        headParams.topMargin = convertHn(370);
        // headGroupView.setLayoutParams(headParams);
      //  seekBar.setThumb(getDrawable(R.drawable.thumb_image));
        seekBar.setLayoutParams(headParams);
        seekBar.setPadding(convertWn(24), 0, convertWn(24), 0);

      //  seekBar.setThumbOffset(convertWn(24));
  //      frame.addView(testView);
        frame.addView(seekBar);
        // seekBar.setPadding(500,100, 50,700);
        seekBar.bringToFront();
        // PageS.setfeeds();
//        seekBar.setTop(350);
//        seekBar.setBottom(100);
//     //   seekBar.setThumb(getDrawable(R.drawable.barseat_1_on));
//        seekBar.setThumbOffset(0);
        seekBar.setSplitTrack(false);


        seekBar.setOnSeekBarChangeListener(this);
        seekBar1 = new SeekBar(this);

        //seekBar.setMin(1);
        seekBar.setMax(100);
        seekBar.setTag(0);
    //    ShapeDrawable thumb = new ShapeDrawable( new RectShape() );
//        thumb.getPaint().setColor( 0x00FF00 );
//        thumb.setIntrinsicHeight( 80 );
//        thumb.setIntrinsicWidth( 30 );
       // Drawable drawable = getNewDrawable(MainActivityf.this,R.drawable.thumb_image, 24, 24);
     //   seekBar.setThumb(drawable);
      // seekBar.setThumb(getDrawable(R.drawable.b1_off));

        //*******************
//        seekBar1.setThumb(getDrawable(R.drawable.thumb_image));
//        seekBar1.setProgressDrawable(getDrawable(R.drawable.adjust));
//        seekBar1.setMinimumHeight(convertHn(3));
//      seekBar1.setOnSeekBarChangeListener(this);
//      //seekBar1.setLeft(convertWn(32));
//      seekBar1.setPadding(convertWn(32), 0, convertWn(32), 0);
//
//        seekBar1.setThumbOffset(convertWn(32));
//        FrameLayout.LayoutParams headParams1 = new FrameLayout.LayoutParams(convertWn(376), convertHn(36));
//      //  headParams1.leftMargin = convertWn(566);
//      //  headParams1.topMargin = convertHn(193);
//        headParams1.setMargins(convertWn(566), convertHn(193), convertWn(60), convertHn(228));
//
//       // headParams1.sep
//        seekBar1.setLayoutParams(headParams1);
//        frame.addView(seekBar1);
//        // seekBar.setPadding(500,100, 50,700);
//        seekBar1.bringToFront();
//        seekBar1.setSplitTrack(false);
//        seekBar2 = new SeekBar(this);
//
//        // seekBar1.setPadding(0,0,0,0);
//        seekBar2.setThumb(getDrawable(R.drawable.thumb_image));
//        seekBar2.setProgressDrawable(getDrawable(R.drawable.adjust));
//        seekBar2.setMinimumHeight(convertHn(3));
//        seekBar2.setOnSeekBarChangeListener(this);
//        seekBar2.setThumbOffset(32);
//
//        seekBar2.setPadding(convertWn(32), 0, convertWn(32), 0);
//
//        seekBar2.setThumbOffset(convertWn(32));
//        seekBar3 = new SeekBar(this);
//
//        // seekBar1.setPadding(0,0,0,0);
//        seekBar3.setThumb(getDrawable(R.drawable.thumb_image));
//        seekBar3.setProgressDrawable(getDrawable(R.drawable.adjust));
//        seekBar3.setMinimumHeight(convertHn(3));
//        seekBar3.setOnSeekBarChangeListener(this);
//       // seekBar3.setThumbOffset(0);
//        seekBar3.setPadding(convertWn(32), 0, convertWn(32), 0);
//
//        seekBar3.setThumbOffset(convertWn(32));
//
//        seekBar.setTag(0);
//        seekBar1.setTag(1);
//        seekBar2.setTag(2);
//        seekBar3.setTag(3);
//        FrameLayout.LayoutParams headParams2 = new FrameLayout.LayoutParams(convertWn(376), convertHn(36));
//       // headParams2.setMargins(convertWn(566), convertHn(360), convertWn(936), convertHn(395));
//        headParams2.leftMargin = convertWn(566);
//        headParams2.topMargin = convertHn(293);
//        seekBar2.setLayoutParams(headParams2);
//        frame.addView(seekBar2);
//        // seekBar.setPadding(500,100, 50,700);
//        seekBar2.bringToFront();
//        seekBar2.setSplitTrack(false);
//
//        FrameLayout.LayoutParams headParams3 = new FrameLayout.LayoutParams(convertWn(376), convertHn(36));
//        // headParams2.setMargins(convertWn(566), convertHn(360), convertWn(936), convertHn(395));
//        headParams3.leftMargin = convertWn(566);
//        headParams3.topMargin = convertHn(388);
//        seekBar3.setLayoutParams(headParams3);
//        frame.addView(seekBar3);
//        // seekBar.setPadding(500,100, 50,700);
//        seekBar3.bringToFront();
//        seekBar3.setSplitTrack(false);
//************
        for (int hh=0;hh<1;hh++) {
            String tmpStat = PageS.feedMap.get(PageS.allDArray[hh+10]);
            if (!tmpStat.equals("0000")) {
                dish(PageS.allDArray[hh+10], tmpStat);
            }
        }

    }

     public BitmapDrawable getNewDrawable(Activity context, int restId, int  dstWidth, int dstHeight){
         Bitmap Bmp = BitmapFactory. decodeResource(context.getResources(), restId);
         Bitmap bmp = Bmp.createScaledBitmap(Bmp, dstWidth, dstHeight, true);
         BitmapDrawable d = new BitmapDrawable(bmp);
         Bitmap bitmap = d.getBitmap();
         if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
             d.setTargetDensity(context.getResources().getDisplayMetrics());
         }
         return d;
     }

    public int convertHn(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = (old * screenHeight) / 600;

        return newx;

    }


    public int convertWn(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = oldx * screenWidth / 1024;

        return newx;

    }

    void refreshui(int keyy)
    {
        //remove old

        removeAll();

        pagestatus.setInit(keyy);

        currentPage = PageS.pageno;
        //pagestatus.allRect = pa
        //invoke event
         mezi = new MeziView(MainActivityf.this);
        //为我们的萌妹子添加触摸事件监听器
        // mezi.setOnTouchListener(new OnTouchListener() {
        //  @Override
        // public boolean onTouch(View view, MotionEvent event) {
        //设置妹子显示的位置

        mezi.bitmapX = 100;
        mezi.bitmapY = 100;
//        mezi.mleft = convertW(0);
//        mezi.mtop = convertH(0);
//        mezi.mwidth = convertW(10);
//        mezi.mheight = convertH(10);

        mezi.mleft = convertWn(0);
        mezi.mtop = convertHn(0);
        mezi.mwidth = convertWn(10);
        mezi.mheight = convertHn(10);
       // mezi.mRes = R.drawable.b2_off;
        mezi.type = 1;
       // mezi.setVisibility(View.INVISIBLE);
        mezi.setClickable(true);
        String allCmdx = cmdheader;
        String tmpTmp = "C1200009";
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        // mezi.setTag(allCmd.toString());
        mezi.setId(0);
        // frame.setTag(allCmd.toString());
        mezi.setOnTouchListener(new TouchListenerx());
       // expandViewTouchDelegate(mezi,0,0,0,0);
       // frame.setClickable(false);

        frame.setEnabled(false);
        frame.addView(mezi,-1);
        frame.setBackgroundResource(PageS.pageback);
     //   frame.setBackgroundResource(R.drawable.a6);
       // frame.addView(mezi,0);
       // frame.invalidate();

        addmezis();
       //
        if(keyy == 0) {
            createSeekb();
        }
        if(keyy == 2) {
            createV();
        }
       //  getaddMezi(5);
        // frame.addView(mezi,maxC);

       // testFeed(5);
       // frame.addView(mezi,1);
        //// add feed status

        /// add original icon for feed type  19 ?
        /// rect mingan for diandong type 16 ?


        //frame.addV
       // pagestatus.setInit(currentPage);
        //addnews setid
        //findallrects
        //getcurrent
       // currentRect =
    }


    public  void createV()
    {
        testfView = new TextView(this);
        // testView.setMargins(convertWn(566), convertHn(268), convertWn(936), convertHn(303));
        //  testfView.setPadding(convertWn(527), convertHn(176), convertWn(827), convertHn(278));
        // testfView.setPadding(convertWn(0), convertHn(0), convertWn(0), convertHn(0));
        // testView.setPadding(187, 156, 422, 278);
        testfView.setText("0.0");
        String tmpStat = PageS.feedMap.get(PageS.allDArray[9]);
        if(!tmpStat.equals("0000"))
        {
            disv(PageS.allDArray[9],tmpStat);
        }

        Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
        testfView.setTypeface(typeface);//第一句话“离离原上草，一岁一枯荣”引入lanti.ttf字体库

        testfView.setTextColor(getResources().getColor(R.color.colorPrimary));
       // testfView.setTextSize(158);
        testfView.setTextSize(79);
        //    testfView.setGravity(Gravity.RIGHT);

        int mWidth = testfView.getMeasuredWidth();
        int mHeight = testfView.getMeasuredHeight();
        FrameLayout.LayoutParams paramsf=new FrameLayout.LayoutParams(convertWn(204),convertHn(114));
        paramsf.leftMargin = convertWn(687) + mWidth/2 ;
        paramsf.topMargin = convertHn(186) +  mHeight / 2;
        //  LinearLayout.LayoutParams paramsf=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        //  paramsf.leftMargin =
        //  paramsf.setMargins(convertWn(427), convertHn(176), convertWn(623), convertHn(278));
        //  paramsf.leftMargin = 0;
        //  testfView.setMar(convertWn(327), convertHn(176), convertWn(623), convertHn(278));
        testfView.setLayoutParams(paramsf);
        frame.addView(testfView,paramsf);
        //    frame.addView(testfView);
        testView = new TextView(this);
        // testView.setMargins(convertWn(566), convertHn(268), convertWn(936), convertHn(303));
        //  testView.setPadding(convertWn(187), convertHn(176), convertWn(422), convertHn(278));
        // testView.setPadding(187, 156, 422, 278);
        testView.setText("0.0");
        String ftmpStat = PageS.feedMap.get(PageS.allDArray[8]);
        if(!ftmpStat.equals("0000"))
        {
            disv(PageS.allDArray[8],ftmpStat);
        }
        //   Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
        testView.setTypeface(typeface);//第一句话“离离原上草，一岁一枯荣”引入lanti.ttf字体库

        testView.setTextColor(getResources().getColor(R.color.colorPrimary));
      //  testView.setTextSize(233);
        testView.setTextSize(116);


        //   LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        FrameLayout.LayoutParams params=new FrameLayout.LayoutParams( convertWn(204),convertHn(114));
        int tWidth = testfView.getMeasuredWidth();
        int tHeight = testfView.getMeasuredHeight();
        params.leftMargin = convertWn(187) + tWidth/2 ;
        params.topMargin = convertHn(166) +  tHeight / 2;
        testView.setLayoutParams(params);
       // this.addContentView(testView,params);
        frame.addView(testView,params);
        //   MainActivityw.AsyncTaskRunner runner = new MainActivityw.AsyncTaskRunner();
        //String sleepTime = "10:0000000123456";
        //  runner.execute();
//        pointValue = new ImageView(this);
//
//        pointValue.setPadding(convertWn(197), convertHn(176), convertWn(352), convertHn(278));
//        pointValue.setImageDrawable(getDrawable(R.drawable.vido_2_off));
//        pointValue.setRotation(135);
//        //   Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
//
//        LinearLayout.LayoutParams paramsv=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
//        pointValue.setLayoutParams(params);
//        this.addContentView( pointValue,params);dis
    }
     //返回键退出程序
   //  @Override
//     public boolean onKeyDown(int keyCode, KeyEvent event) {
//         if (keyCode == KeyEvent.KEYCODE_BACK
//                 && event.getAction() == KeyEvent.ACTION_DOWN) {
////            for (Activity activity : ParameterSetActivity.activityList) {
////                activity.finish();
////            }
//             this.finish();
//             System.exit(0);
//             return true;
//         }
//         return super.onKeyDown(keyCode, event);
//     }
    public  void addmezis()
    {


        Rect tmprect = new Rect() ;
        Rect tmprecto = new Rect() ;
        int tmp =PageS.allRect.length;
        maxC = tmp ;
        for (int w=0; w<tmp;w++) {
           // tmprecto = convertRect(PageS.allRect[w]);


            tmprecto = PageS.allRect[w];
            MeziView mezii = new MeziView(MainActivityf.this);

          //  mezii.setOnTouchListener(new TouchListenerx());
            // mezi.setOnTouchListener(new OnTouchListener() {
            //  @Override
            // public boolean onTouch(View view, MotionEvent event) {


          //  expandViewTouchDelegate(mezii,0,0,0,0);
          //  mezi.bitmapX = 100;
          //  mezi.bitmapY = 0;
//            mezii.mleft = convertW(tmprecto.left);
//            mezii.mtop = convertH(tmprecto.top);
//            mezii.mwidth = convertW(tmprecto.width());
//            mezii.mheight = convertH(tmprecto.height());

            mezii.mleft = convertWn(tmprecto.left);
            mezii.mtop = convertHn(tmprecto.top);
            mezii.mwidth = convertHn(tmprecto.width());
          //  mezii.mheight = convertHn(tmprecto.height());

            mezii.mheight = convertHn(tmprecto.height());

            mezii.mRes = PageS.offArray[w];
            String addr = PageS.feedDArray[w];
            boolean bool1 = PageS.feedMap.containsKey(addr);
            String tmpS = PageS.feedMap.get(addr);
            boolean bool2 = (tmpS == null)? false:(tmpS.equals("0001"));


            mezii.type = PageS.nodeArray[w];
         //   mezii.setClickable(true);
            String allCmdx = cmdheader;
            String tmpTmp = "C1200009";
            // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
            allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
            StringBuffer allCmd = CRC16.crc16x(allCmdx);
            // mezi.setTag(allCmd.toString());
            mezii.setId(w + 1);
            // frame.setTag(allCmd.toString());
            // mezii.setOnTouchListener(new TouchListenerx());

            //  frame.addView(mezi,0);
          //  frame.setBackgroundResource(pagestatus.pageback);
           // frame.addView(mezii);
            frame.addView(mezii,w);
            if(bool1 && bool2)
            {
                mezii.mRes = PageS.onArray[w];
                mezii.repaint();
                //testFeed(w,true);
            }
          //  testFeed(6);
           // frame.getChildAt()
        }
    }


     private  void testsFeed(int myPosition,boolean onff)
     {
         if(myPosition > 0) {
             newm = (MeziView) frame.getChildAt(myPosition );


             String aaaa = newm.getId() + "|" + myPosition;
             Log.e("feedTest", aaaa);

             if (newm != null) {
                 if(onff) {
                    // newm.mleft = convertWn(0);
                   //  newm.mtop = convertHn(0);
                   //  newm.lv = 92;
                   //  newm.mwidth = convertWn(78);
                   //   newm.mheight = convertHn(78);
                     newm.ho = 27;
                     newm.lv = 116;
                     newm.la = 242;
                     newm.li = 140;
                     newm.mleft = (int) (newm.mleft - 10);
                     newm.mtop = (int) (newm.mtop -10);
                      // newm.lv = 92;
                     newm.mwidth = (int) (newm.mwidth +20);
                     newm.mheight = (int) (newm.mheight +20);
                 }
                 else
                 {
                    // newm.mleft = convertWn(0);
                   //  newm.mtop = convertHn(0);
                     newm.ho = 255;
                     newm.lv = 255;
                     newm.la = 255;
                     newm.li = 125;
                     newm.mleft =  (int) (newm.mleft + 10);
                     newm.mtop = (int) (newm.mtop + 10);
                     // newm.lv = 92;
                     newm.mwidth = (int) (newm.mwidth -20);
                     newm.mheight = (int) (newm.mheight -20);
                     //= convertWn(91);
                  //   newm.mheight = convertHn(91);
                 }
                 // newm.mRes = onff ? PageS.onArray[myPosition] : PageS.offArray[myPosition];
                 // newm.mRes = R.drawable.cbbm_television;
                 newm.repaint();
                 // newm.postInvalidate();
                 // newm.notify();
             }
         }
     }

    private  void testFeed(int myPosition,boolean onff)
    {
        if(myPosition > 0) {
             newm = (MeziView) frame.getChildAt(myPosition );


            String aaaa = newm.getId() + "|" + myPosition;
            Log.e("feedTest", aaaa);

            if (newm != null) {

                newm.mRes = onff ? PageS.onArray[myPosition] : PageS.offArray[myPosition];
               // newm.mRes = R.drawable.cbbm_television;
                newm.repaint();
               // newm.postInvalidate();
               // newm.notify();
            }
        }
    }
    public MeziView getaddMezi(int seq)
    {
       // MeziView newm = new MeziView();
        Rect tmprecto = new Rect();
        tmprecto = PageS.allRect[seq];
        MeziView mezii = new MeziView(MainActivityf.this);
     //   mezii.setActivated(false);

        // mezi.setOnTouchListener(new OnTouchListener() {
        //  @Override
        // public boolean onTouch(View view, MotionEvent event) {


        //  mezi.bitmapX = 100;
        //  mezi.bitmapY = 0;
        mezii.mleft = convertWn(tmprecto.left);
        mezii.mtop = convertHn(tmprecto.top);
        mezii.mwidth = convertWn(tmprecto.width());
        mezii.mheight = convertHn(tmprecto.height());
        mezii.mRes = PageS.offArray[seq];
        mezii.type = PageS.nodeArray[seq];
        //mezii.setO
        String allCmdx = cmdheader;
       // String tmpTmp = "C1200009";
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
       // allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
      //  StringBuffer allCmd = CRC16.crc16x(allCmdx);
        // mezi.setTag(allCmd.toString());
        mezii.setId(seq + 1);
        // frame.setTag(allCmd.toString());
        // mezii.setOnTouchListener(new TouchListenerx());

        //  frame.addView(mezi,0);
        //  frame.setBackgroundResource(pagestatus.pageback);
       // frame.addView(mezii, maxC);
        frame.addView(mezii);
        maxC =  maxC + 1;
        return  mezii;

    }

    public  String getCmd(int key)
    {
        String allCmdx = cmdheader;

        String tmpTmp = "C1200009";
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);



        //mezi.setTag(allCmd.toString());
        return allCmd.toString();
    }

    int getCurSel(Rect[] allrect ,int x,int y)
    {

      //  if (tempRect.contains((int) x, (int) (y)))
        Rect tmprect = new Rect() ;
        Rect tmprecto = new Rect() ;
        int tmp = allrect.length;
        for (int w=0; w<tmp;w++)
        {
            tmprecto = convertRect(allrect[w]);
            if (tmprecto.contains(x,y))
            {
                tmprect = tmprecto;
                return  w;
            }
        }
        return  -1;
    }

    @Override
    protected void onDestroy() {
        // uartJni.close(fd);
        uartJnit.sclose();
        super.onDestroy();
    }
    @Override
    protected void onPause() {
       // uartJni.close(fd);
 //       fd =  uartJnit.getInstance().fd;
       // uartJnit.sclose();
//        uartJnit.close(fd);
        super.onPause();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //  super.onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_test);


        // Example of a call to a native method
        // TextView tv = (TextView) findViewById(R.id.sample_text);
        //tv.setText(stringFromJNI());
        // gv = (GridLayout) findViewById(R.id.gridlayout1);
       frame = (myFrameLayout) findViewById(R.id.gridlayout1);

        PageS.setfeeds();
         refreshui(currentPage);
      //  testFeed(5);

       // mServiceIntent = new Intent(this, BackService.class);


     //  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
     //           WindowManager.LayoutParams.FLAG_FULLSCREEN);


        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        //  ActionBar actionBar = getActionBar();
        //  actionBar.hide();


        // final MeziView mezi = new MeziView(MainActivity.this);


       // pagestatus.setInit(currentPage);
      // refreshui(currentPage);



       // tempRect = new Rect(rconvertW(mezi.mleft) , rconvertH(mezi.mtop), rconvertW(mezi.mleft + mezi.mwidth) ,rconvertH(mezi.mtop + mezi.mheight));
         //tempRect = new Rect(mezi.mleft , mezi.mtop, mezi.mleft + mezi.mwidth ,mezi.mtop + mezi.mheight);

        // mezi.getHitRect(tempRect);
       // mezi.getDrawingRect(tempRect);
        //mezi.type = 0;
        String allCmdx = cmdheader;

        String tmpTmp = "C1200009";
       // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);



       // mezi.setTag(allCmd.toString());
        //mezi.setId(2);
       // frame.setTag(allCmd.toString());
      //  mezi.setOnTouchListener(new TouchListenerx());


        // mezi.setTag();
      //  mezi.setOnTouchListener(new TouchListenerx());
        //  @Override
        // public boolean onTouch(View view, MotionEvent event) {
        //调用重绘方法
        // mezi.invalidate();
        //    return true;
        //   }
        //  });
       // frame.addView(mezi);
        // final MeziView mezi1 = new MeziView(MainActivity.this);
       // MeziView mezi1 = new MeziView(MainActivity.this);
        //为我们的萌妹子添加触摸事件监听器
        // mezi.setOnTouchListener(new OnTouchListener() {
        //  @Override
        // public boolean onTouch(View view, MotionEvent event) {
        //设置妹子显示的位置
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;


//        mezi1.bitmapX = 100;
//        mezi1.bitmapY = 300;
//        //  mezi1.mleft = convertW(774);
//        mezi1.mleft = convertW(113);
//        mezi1.mtop = convertH(608);
//        mezi1.mwidth = convertW(141);
//        mezi1.mheight = convertH(139);
//        mezi1.mRes = R.drawable.vido_1_on;
//        //  mezi1.type = 1;
//
//        mezi1.setTag(allCmd.toString());
//        //tempRect = new Rect(mezi1.mleft , mezi1.mtop, mezi1.mleft + mezi1.mwidth ,mezi1.mtop + mezi1.mheight);
//
//        mezi1.setId(1);

       // frame
       // mezi1.setOnTouchListener(new TouchListenerx());

     //  mezi.setOnTouchListener(new OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View view, MotionEvent event) {
//                //设置妹子显示的位置
//                mezi.bitmapX = event.getX();
//                mezi.bitmapY = event.getY();
//                //调用重绘方法
//                mezi.invalidate();
//                return true;
//            }
//        });


        // Resources resources = getContext().getResources();
        // Drawable btnDrawable = resources.getDrawable(R.drawable.a3);
      //  frame.setBackgroundResource(R.drawable.a1);
        //  frame.setBackground(btnDrawable)；

        //frame.addView(mezi1);
        //   frame.removeAllViews();
        //frame.removeViewAt(1);


        // btn.setWidth(100);
       // btn.setText(String.valueOf(count));


        //gv.addView(plusText, plusParams);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        //int count=layout.getChildCount(); if (count-3>0)
        // { layout.removeViewAt(count-1); } } });
//        mServiceIntent = new Intent(this, BackService.class);
//        bindService(mServiceIntent, connection, BIND_AUTO_CREATE);
//
//        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
//        mIntentFilter = new IntentFilter();
//        mIntentFilter.addAction(BackService.HEART_BEAT_ACTION);
//        mIntentFilter.addAction(BackService.MESSAGE_ACTION);
//        mIntentFilter.addAction(BackService.STATE_FAIL_ACTION);
//        mIntentFilter.addAction(BackService.STATE_SUCCESS_ACTION);
//        //
//
//        mReciver = new MessageBackReciver();
//
//        mLocalBroadcastManager.registerReceiver(mReciver, mIntentFilter);

        userInfo =  getSharedPreferences("user_info",
                MODE_PRIVATE);

        testtView = new TextView(this);
        //这里的Textview的父layout是ListView，所以要用ListView.LayoutParams
      //  ListView.LayoutParams layoutParams = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, ListView.LayoutParams.WRAP_CONTENT);
       // textView.setLayoutParams(layoutParams);
        testtView.setPadding(20, 0, 20, 0);
        testtView.setText("this is used for testing");
        testtView.setTextColor(getResources().getColor(R.color.colorAccent));
        testtView.setTextSize(18);


        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        testtView.setLayoutParams(params);
        this.addContentView(testtView,params);
        testtView.setVisibility(View.INVISIBLE);
        AsyncTaskRunner runner = new AsyncTaskRunner();
        //String sleepTime = "10:0000000123456";
        runner.execute();
        makeStatusBarTransparent(this);

    }


    public int convertW(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = oldx * screenWidth / 2048;

        return newx;

    }

    public  Rect convertRect(Rect old)
    {
        return  new Rect(convertWn(old.left),convertHn(old.top),convertWn(old.right),convertHn(old.bottom));
    }
    public int convertH(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = (old * screenHeight) / 1536;

        return newx;

    }

    protected int rconvertW(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = (oldx *  2048) / screenWidth;

        return newx;

    }

    protected int rconvertH(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = (1536 * old) / screenHeight;

        return newx;

    }

    protected View createButton(int index) {
        final Button btn = new Button(this);
        btn.setId(index++);
        Log.d("da", "id is" + btn.getId());

        btn.setWidth(40);
        btn.setHeight(100);
        //GridLayout.LayoutParams mParams = new GridLayout.LayoutParams(
        //btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
        //       LinearLayout.LayoutParams.WRAP_CONTENT));
        // btn.set
        // btn.setLayoutParams(new GridLayout.LayoutParams(GridLayout.LayoutParams.MATCH_PARENT, GridLayout.LayoutParams.MATCH_PARENT));
        btn.setText("okc");
        return btn;
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    // Used to load the 'native-lib' library on application startup.
    static {
        //       System.loadLibrary("native-lib");
    }


    private boolean isTouchPointInView(View view, int x, int y) {
        if (view == null) {
            return false;
        }
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int left = location[0];
        int top = location[1];
        int right = left + view.getMeasuredWidth();
        int bottom = top + view.getMeasuredHeight();
        //view.isClickable() &&
        if (y >= top && y <= bottom && x >= left
                && x <= right) {
            return true;
        }
        return false;
    }



    @Override
    protected void onStart() {
        super.onStart();
       // mClient.connect();
        userInfo.registerOnSharedPreferenceChangeListener(mListener);
    }

    @Override
    protected void onStop() {
        userInfo.unregisterOnSharedPreferenceChangeListener(mListener);
        super.onStop();
    }
    @Override
    protected void onResume() {
//        String device = "/dev/ttyS3";
//        fd = uartJni.open(device, 115200);
//        Log.d(TAG, "open the device of " + device + ", fd is: " + fd);
       fd =  uartJnit.getInstance().fd;
        super.onResume();

        handler.postDelayed(new Runnable() {
            String tmpstr = "";
            @Override
            public void run() {


                // int read_count = uartJni.read(fd, read_buf, read_buf.length);
               // fd = uartJnit.fd;
                try {
                    int read_count = uartJni.read(fd, read_buf, read_buf.length);

                    if (read_count < 0) {
                        read_count = 0;
                    }
                    if (read_count > 40) {
                        read_count = 40;
                    }

                tmpstr = toHex(read_buf, read_count).toString();
                }
                catch(Exception ex)
                {

                }
                if (!tmpstr.equals("")) {
                    Message cmdmsg = new Message();
                    cmdmsg.what = 1;
                    Bundle bcmd = new Bundle();
                    bcmd.putString("alltext", tmpstr);
                    cmdmsg.setData(bcmd);
                    boolean xx = uHandler.sendMessage(cmdmsg);
                }
                //while
                handler.postDelayed(this,200);
            }  //run

        },1000);
      //    mServiceIntent = new Intent(this, BackService.class);
      //    bindService(mServiceIntent, connection, BIND_AUTO_CREATE);
      //    mLocalBroadcastManager.registerReceiver(mReciver, mIntentFilter);
///////////??????
    }




    private class TouchListenerx implements View.OnTouchListener {
        private boolean longClicked;
        private boolean upClicked;
        private int downtimes = 0;
        private int uptimes = 0;
        private int failTime;
        //private IBackService xBackService;
//        private TouchListenerx(IBackService abak) {
//         //   xBackService = abak;
//        }

        private TouchListenerx() {
            //   xBackService = abak;
        }


//        public boolean dispatchTouchEvent(MotionEvent event) {
//            if (this != null && this.onTouch(this, event)) {
//
//
//
//
//                return true;
//            }
//            return onTouchEvent(event);
//        }


        public void okD(String cmdOne,int ttt)
        {
            Message msg = new Message();
            //  if (isSend) {
            msg.what = ttt;
            msg.obj = cmdOne;
            Bundle bundle = new Bundle();
            bundle.putString("jmppageno", cmdOne);
//                    bundle.putString("feedStatus", deviceStaus);
            msg.setData(bundle);
            //  Integer.parseInt(pagestatus.cmdArray[1]);
            mHandler.sendMessage(msg);
        }

        public boolean onTouch(View v, MotionEvent event) {

            //  iBackService.
            int x = (int) event.getX();
            int y = (int) event.getY();
            currentPosition = getCurSel(PageS.allRect,x,y);
           // final String cmdAll = v.getTag().toString();
           // int selno = getCurSel(pagestatus.allRect,x,y)
            //  String cmdAll = pagestatus.cmdArray[currentPosition];

          //   final String cmd = cmdAll.substring(0, 22);

            //int selno = pagestatus

           // testFeed(6);
           // jmpPostion = pagestatus.cmdArray[currentPosition];
            Log.e("touchTAG", "view:"  + v.getId());
           // int x = (int) event.getRawX();
           // int y = (int) event.getRawY();
          //  Rect tmpRect = new Rect();
          //          v.getHitRect(tmpRect);

            if(currentPosition!=-1){
                String cmdOne = PageS.cmdArray[currentPosition];
                int mmtype = pagestatus.typeArray[currentPosition];


               // pageS.
                if (mmtype == 20)
                {
                 //   okD(currentPosition + "",4);
                    //放于cmd数组 双重健壮性检查
                   // refreshui(1);
                    //发消息更新界面
                   // return true;
                    Message msg = new Message();
                    //  if (isSend) {
                    msg.what = 3;
                     msg.obj = cmdOne;
                     Bundle bundle = new Bundle();
                    bundle.putString("jmppageno", cmdOne);
//                    bundle.putString("feedStatus", deviceStaus);
                     msg.setData(bundle);
                  //  Integer.parseInt(pagestatus.cmdArray[1]);
                    mHandler.sendMessage(msg);
                    return  true;
                }
               // final String cmd = cmdAll.substring(0, 22);
                //-1
           // if (isTouchPointInView(v, x, y)) {
           // if (tempRect.contains((int) x, (int) (y))) {
                //  iosInterceptFlag = true;
                //   return super.dispatchTouchEvent(ev);

                //do
                //  event.getY

                 //cmd = cmdAll.substring(0, 22);
               // pagestatus.cmdArray[currentPosition];
                String origin = "5AA50883192001001F"; //19E2
                String allCmdx = cmdheader;
               // String tmpTmp = "C1200009";
                String tmpTmp = cmdOne;
                // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
                allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
                StringBuffer allCmd = CRC16.crc16x(allCmdx);
                final String cmd = allCmd.substring(0,22);
               // String crcString = "83192001001F";
              //  String crcString =  pagestatus.cmdArray[currentPosition];
              //  String nexts = "5aa5078200030000ac1e";
               // String crcString = cmdOne ;
             //   StringBuffer exCmd = CRC16.crc16(crcString);


                longClicked = false;
                upClicked = false;
                if (event.getAction() == 0) {
                   // okD(currentPosition + "",7);

                    testsFeed(currentPosition,true);
                    new Thread() {
                        public void run() {
                            super.run();


                            if (!longClicked) {
                                try {
                                 //   if (uartJint != null) {
                                        boolean isSendx = false;
                                       if (downtimes < 1) {
                                            downtimes = downtimes++;
                                            isSendx = uartJnit.getInstance().sendCmds(cmd);

                                            longClicked = true;
                                        }

                                        Log.e("send TAG", "send down: " + cmd);
                                        Message msg = new Message();
                                        if (isSendx) {
                                            msg.what = 1;

                                            longClicked = true;


                                            Log.e("send TAG", "send down" + cmd + "success");
                                        } else {


                                            Log.e("TAG", "send down  :" + cmd + "failed!");
//
                                        }
                                //    }
//
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                try {
                                    Thread.sleep((long) TIMER_INTERVAL);
                                } catch (InterruptedException e2) {
                                    e2.printStackTrace();

                                }
                            }

                        }
                    }.start();
                } else if (event.getAction() == 1) {
                    {

                      //  okD(currentPosition + "",8);
                        testsFeed(currentPosition,false);
                        new Thread() {
                            public void run() {
                                super.run();


                                if (!upClicked) {
                                    String tmp = cmd.substring(10, 11);
                                    if (tmp.equals("2")) {

                                        try {
                                            //getExchangeCmd()

                                  //          if ((iBackService != null) && (cmd.length() == 22)) {
                                            if (cmd.length() == 22) {

                                                boolean isSendy = false;

                                                Log.e("TAG", "send  dian:" + TransformUtils.getExchangeCmd(cmd));

                                                if (uptimes < 1) {
                                                    uptimes = uptimes++;
                                                    isSendy = uartJnit.getInstance().sendCmds(TransformUtils.getExchangeCmd(cmd));

                                                    upClicked = true;
                                                }
                                                Message msg = new Message();
                                                if (isSendy) {
                                                    msg.what = 1;
                                                    msg.obj = currentPosition;

                                                    upClicked = true;


                                                    Log.e("TAG", "send dian:" + cmd + "success");
                                                } else {


                                                    Log.e("TAG", "send dian " + cmd + " failed!");

                                                }

                                       }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }.start();

                        try {
                            Thread.sleep((long) TIMER_INTERVAL);
                        } catch (InterruptedException e2) {
                            e2.printStackTrace();

                        }

                    }

                    //return true;
                }
            }

                 return  true;
            }
        }

    public static String toHex(byte[] buffer,int read_count) {
        StringBuffer sb = new StringBuffer(read_count * 2);
        for (int i = 0; i < read_count; i++) {
            sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 15, 16));
        }
        return sb.toString();
    }

private class AsyncTaskRunner extends AsyncTask<Void,  String, Void> {

    private String resp;
    ProgressDialog progressDialog;
    LocalServerSocket serverSocket;

    @Override
    protected Void doInBackground(Void... params) {
       // publishProgress("Sleeping..."); // Calls onProgressUpdate()

          //  for(;;){

                    try {
                        //socketAddress需跟localSocket地址一致，否则无法连接上

                        serverSocket = new LocalServerSocket(SOCKET_ADDRESS);

                       // LocalSocket receiveSocket = serverSocket.accept();


                        //设置缓冲大小
                      //  receiveSocket.setReceiveBufferSize(256*4);


                        BufferedReader reader;
                        String message;
                        //final StringBuffer buffer;
                        String line = "";
                        while (true) {



                            LocalSocket accept = serverSocket.accept();
                            InputStream ips = accept.getInputStream();
                            ByteArrayOutputStream byteOps = new ByteArrayOutputStream();
                            byte[] buf = new byte[1024];
                            int len = -1;
                            while((len = ips.read(buf)) != -1){
                                byteOps.write(buf, 0, len);
                            }

                            byte[] array = byteOps.toByteArray();
                            String msg = new String(array);
                          //  showToat(msg);
                            ips.close();
                            accept.close();



                            publishProgress(msg);
                        }

                      //  publishProgress(); // Invokes onProgressUpdate()
                        //localSocket.setSendBufferSize(ConstantConfig.BUFFER_SIZE);
                    } catch (Exception e) {
                        e.printStackTrace();
                       // LoggerHelper.d("Waiting to be linked to a bug,error:" + e.toString());
                      //  return false;
                    }




            return null;
    }


    @Override
    protected void onPostExecute(Void result) {
        // execution of result of Long time consuming operation
       //progressDialog.dismiss();
      //  finalResult.setText(result);
        testView.setText("finished");
    }


    @Override
    protected void onPreExecute() {
      //  progressDialog = ProgressDialog.show(MainActivity.this,
      //          "ProgressDialog",
      //          "Wait for "+time.getText().toString()+ " seconds");
        resp = "TransformUtils.comingdata";
    }


    @Override
    protected void onProgressUpdate(String... values) {
       // String msg = userInfo.getString("user_info", "0000");


        // testView.setText(text[0]);
       // String msgsource = TransformUtils.comingdata;
       // String firstFour = msgsource.substring(0, 25);
             testView.setText(values[0]);
      //  testView.setText(text[0]);
        // Things to be done while execution of long running operation is in
        // progress. For example updating ProgessDialog
    }
}
}